/*
Copyright 2021 LuJun

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is furnished 
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

namespace lcc {

const TAG = "lcc/database/database.ts";

/**
 * @zh
 * 数据库类型
 */
export enum DatabaseType {
	/**
     * @zh
	 * Mysql数据库
	 */
	MYSQL = 1,
}

/**
 * @zh
 * 数据库基类
 */
export class Database extends cocos.event.EventTarget {

	/**
     * @zh
	 * 数据库名称
	 */
	protected _name:string = null;

	/**
     * @zh
	 * 数据库类型
	 */
	protected _type:DatabaseType = null;

	/**
     * @zh
	 * 构造函数
     * 
	 * @param name - 名称
	 * @param type - 类型
	 */
	constructor(name:string, type:DatabaseType){
		super();
		this._name = name;
		this._type = type;
	}
	
	/**
     * @zh
	 * 获得名称
	 */
	public getName(){
		return this._name;
	}
	
	/**
     * @zh
	 * 获得类型
	 */
	public getType(){
		return this._type;
	}
	
	/**
     * @zh
	 * 配置数据库<br/>
     * 子类中应该重写该函数
     * 
	 * @param config - 配置对象，每个类型的数据库有不同的配置
	 */
	public config(config:any){}
	
	/**
     * @zh
	 * 连接数据库<br/>
     * 子类中应该重写该函数
	 */
	public async connect():Promise<boolean>{
        return true;
    }

	/**
     * @zh
	 * 断开数据库<br/>
     * 子类中应该重写该函数
	 */
	public async disconnect():Promise<boolean>{
        return true;
    }
	
	/**
     * @zh
	 * 更新数据库<br/>
     * 如果需要，子类中应重写该函数
     * 
	 * @param dt - 间隔时间
	 */
	public onUpdate(dt:number){}

	/**
     * @zh
	 * 获得连接
	 */
	public async getConnection():Promise<Connection>{
		return null;
	}

	/**
     * @zh
	 * 执行查询
     * 
	 * @param callback - 查询回调函数，应该再回调函数中执行查询操作，并且函数会返回回调函数返回的结果，默认返回null
	 */
	public async doQuery(callback:(con:Connection)=>Promise<any>){
		DEBUG.DATABASE && logMgr.debug(TAG, `${this.getName()} doQuery`);
		let con = await this.getConnection();
		if(con){
            let result = null;
            try {
                result = await callback(con);
            }catch(e){
                lcc.logMgr.error(TAG, e);
            }
			con.release();
			DEBUG.DATABASE && logMgr.debug(TAG, `${this.getName()} doQuery ${result}`);
			return result;
		}
	}

	/**
     * @zh
	 * 执行事务<br/>
     * 如果回调函数返回!!false，则表示事务失败，会执行回滚操作，否则会提交事务<br/>
     * 函数返回回调函数的结果
     * 
	 * @param callback - 事务回调函数，应该再回调函数中执行事务操作
	 */
	public async doTransaction(callback:(con:Connection)=>Promise<boolean>){
		DEBUG.DATABASE && logMgr.debug(TAG, `${this.getName()} doTransaction`);
		let con = await this.getConnection();
		if(con){
			let result = await con.beginTransaction();
			DEBUG.DATABASE && logMgr.debug(TAG, `${this.getName()} beginTransaction ${result}`);
			if(result){
                try {
                    result = await callback(con);
                }catch(e){
                    lcc.logMgr.error(TAG, e);
                }
				if(result){
					if(!(await con.commit())){
						await con.rollback();
					}
				}else{
					await con.rollback();
				}
			}
			con.release();
			DEBUG.DATABASE && logMgr.debug(TAG, `${this.getName()} doTransaction ${result}`);
			return result;
		}
	}
}

}
